﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Configuration;
using System.Web;

namespace FrienDev.BusinessRules
{
    /// <summary>
    /// 页面访问验证模块
    /// </summary>
    public class AuthenticationModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.AcquireRequestState += new EventHandler(context_AcquireRequestState);
        }

        #endregion

        private void context_AcquireRequestState(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;
            string path = context.Request.Path.ToLower();
            
            // 只处理aspx文件，因为其他文件无法获得Session对象，无法判断是否已经登录
            if (path.EndsWith(".aspx"))
            {
                // 如果用户没有登录
                if (!UserRules.Instance.IsCurrentUserLogined)
                {
                    // 对于公共文件夹和根目录的文件不做判断
                    if (!path.StartsWith("/" + ApplicationSettings.PUBLICFOLDERNAME.ToLower() + "/") &&
                        !(path.LastIndexOf("/") == 0))
                    {
                        // 跳转到公共页面首页
                        //context.Response.Redirect(ApplicationSettings.PUBLICDEFAULTFILENAME);
                        context.Response.Redirect("/webauth-handler.aspx?action=logout");
                        context.Response.End();
                    }
                }
            }
        }
    }
}
